import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Modal, message, Input, Select, List, Typography } from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const EditParamForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleEditParamVisible,
    handleEditParam,
    fields,
    dataTypes,
    detail,
  } = props;
  const okHandle = () => {
    form.validateFields((error, fieldsValue) => {
      if (error) return;
      handleEditParam(fieldsValue, form);
    });
  };
  const renderOption = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));
  return (
    <Modal
      title={formatMessage({ id: 'app.dm.product.service.param.add' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      onCancel={() => handleEditParamVisible()}
    >
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.name' })} colon={false}>
          {form.getFieldDecorator('name', {
            initialValue: detail.name,
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.service.param.name.place' }),
              },
            ],
          })(
            <Input
              placeholder={formatMessage({ id: 'app.dm.product.service.param.name.place' })}
            />,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.label' })} colon={false}>
          {form.getFieldDecorator('label', {
            initialValue: detail.label,
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.service.param.label.place' }),
              },
            ],
          })(
            <Input
              placeholder={formatMessage({ id: 'app.dm.product.service.param.label.place' })}
            />,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.service.param.protocolfieldlabel' })}
          colon={false}
        >
          {form.getFieldDecorator('protocolFieldLabel', {
            initialValue: detail.protocolFieldLabel,
            rules: [
              {
                required: true,
                message: formatMessage({
                  id: 'app.dm.product.service.param.protocolfieldlabel.place',
                }),
              },
            ],
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({
                id: 'app.dm.product.service.param.protocolfieldlabel.place',
              })}
            >
              {renderOption(fields)}
            </Select>,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.type' })} colon={false}>
          {form.getFieldDecorator('type', {
            initialValue: detail.type,
            message: formatMessage({ id: 'app.dm.product.service.param.type.place' }),
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({ id: 'app.dm.product.service.param.type.place' })}
            >
              {renderOption(dataTypes)}
            </Select>,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.val' })} colon={false}>
          {form.getFieldDecorator('value', {
            initialValue: detail.value,
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.service.param.val.place' }),
              },
            ],
          })(
            <Input placeholder={formatMessage({ id: 'app.dm.product.service.param.val.place' })} />,
          )}
        </FormItem>
      </div>
    </Modal>
  );
});

const AddParamForm = Form.create()(props => {
  const { modalVisible, form, handleAddParamVisible, handleAddParam, fields, dataTypes } = props;

  const okHandle = () => {
    form.validateFields((error, fieldsValue) => {
      if (error) return;
      handleAddParam(fieldsValue, form);
    });
  };
  const renderOption = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));
  return (
    <Modal
      title={formatMessage({ id: 'app.dm.product.service.param.add' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      onCancel={() => handleAddParamVisible()}
    >
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.name' })} colon={false}>
          {form.getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.service.param.name.place' }),
              },
            ],
          })(
            <Input
              placeholder={formatMessage({ id: 'app.dm.product.service.param.name.place' })}
            />,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.label' })} colon={false}>
          {form.getFieldDecorator('label', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.service.param.label.place' }),
              },
            ],
          })(
            <Input
              placeholder={formatMessage({ id: 'app.dm.product.service.param.label.place' })}
            />,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.service.param.protocolfieldlabel' })}
          colon={false}
        >
          {form.getFieldDecorator('protocolFieldLabel', {
            rules: [
              {
                required: true,
                message: formatMessage({
                  id: 'app.dm.product.service.param.protocolfieldlabel.place',
                }),
              },
            ],
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({
                id: 'app.dm.product.service.param.protocolfieldlabel.place',
              })}
            >
              {renderOption(fields)}
            </Select>,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.type' })} colon={false}>
          {form.getFieldDecorator('type', {
            message: formatMessage({ id: 'app.dm.product.service.param.type.place' }),
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({ id: 'app.dm.product.service.param.type.place' })}
            >
              {renderOption(dataTypes)}
            </Select>,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.service.param.val' })} colon={false}>
          {form.getFieldDecorator('value', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.service.param.val.place' }),
              },
            ],
          })(
            <Input placeholder={formatMessage({ id: 'app.dm.product.service.param.val.place' })} />,
          )}
        </FormItem>
      </div>
    </Modal>
  );
});

@connect(({ product, loading }) => ({
  product,
  loading: loading.models.product,
}))
@Form.create()
class AddProductServiceForm extends PureComponent {
  state = {
    paramIndex: 0,
    paramList: [],
    addParamModalVisible: false,
    editParamModalVisible: false,
  };

  handleAddParamVisible = flag => {
    this.setState({
      addParamModalVisible: !!flag,
    });
  };

  handleEditParamVisible = flag => {
    this.setState({
      editParamModalVisible: !!flag,
    });
  };

  handleEditParam = (fields, form) => {
    const { paramList, paramIndex } = this.state;
    let flag = true;
    paramList.map((item, index) => {
      if (item.label === fields.label && index !== paramIndex) {
        flag = false;
        return item;
      }
      return item;
    });
    if (!flag) {
      message.error({
        content: formatMessage({ id: 'app.dm.product.service.param.label.repeat.place' }),
        key: 1,
      });
      return;
    }
    // 修改index位置
    const obj = {
      name: fields.name,
      label: fields.label,
      protocolFieldLabel: fields.protocolFieldLabel,
      type: fields.type,
      value: fields.value,
    };
    this.setState({
      paramList: paramList.map((item, _index) => (paramIndex === _index ? { ...obj } : item)),
    });
    this.handleEditParamVisible();
    form.resetFields();
  };

  handleAddParam = (fields, form) => {
    const { paramList } = this.state;
    let flag = true;
    paramList.map(item => {
      if (item.label === fields.label) {
        flag = false;
        return item;
      }
      return item;
    });
    if (!flag) {
      message.error({
        content: formatMessage({ id: 'app.dm.product.service.param.label.repeat.place' }),
        key: 1,
      });
      return;
    }
    const obj = {
      name: fields.name,
      label: fields.label,
      protocolFieldLabel: fields.protocolFieldLabel,
      type: fields.type,
      value: fields.value,
    };
    this.setState({
      paramList: [...paramList, obj],
    });
    this.handleAddParamVisible();
    form.resetFields();
  };

  handleRemoveItem = index => {
    const { paramList } = this.state;
    const tempList = paramList;
    tempList.splice(index, 1);
    this.setState(prevState => {
      delete prevState.paramList;
      return prevState;
    });
    this.setState({
      paramList: tempList,
    });
  };

  editParam = (item, index) => {
    const { dispatch } = this.props;
    this.setState({
      paramIndex: index,
    });
    this.handleEditParamVisible(true);
    dispatch({
      type: 'product/fetchServiceParam',
      payload: { paramItem: item },
    });
  };

  clearParamList = () => {
    this.setState({
      paramList: [],
    });
  };

  render() {
    const {
      modalVisible,
      form,
      handleModalVisible,
      handleAdd,
      product: { fieldList, dataTypeList, serviceParamDetail },
    } = this.props;
    const { paramList, addParamModalVisible, editParamModalVisible } = this.state;
    const { clearParamList } = this;
    const okHandle = () => {
      form.validateFields((error, fieldsValue) => {
        if (error) return;
        if (paramList.length === 0) {
          message.error({
            content: formatMessage({ id: 'app.dm.product.service.info.params.place' }),
            key: 1,
          });
          return;
        }
        handleAdd(fieldsValue, paramList, form, clearParamList);
      });
    };

    const addParamProps = {
      handleAddParamVisible: this.handleAddParamVisible,
      fields: fieldList,
      dataTypes: dataTypeList,
      handleAddParam: this.handleAddParam,
    };

    const editParamProps = {
      handleEditParamVisible: this.handleEditParamVisible,
      fields: fieldList,
      dataTypes: dataTypeList,
      handleEditParam: this.handleEditParam,
      detail: serviceParamDetail,
    };

    return (
      <Modal
        title={formatMessage({ id: 'app.dm.product.service.add' })}
        destroyOnClose
        visible={modalVisible}
        width={618}
        onCancel={() => handleModalVisible()}
        onOk={okHandle}
      >
        <div style={{ width: 530, paddingLeft: 44 }}>
          <FormItem label={formatMessage({ id: 'app.dm.product.service.info.name' })} colon={false}>
            {form.getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'app.dm.product.service.info.name.place' }),
                },
              ],
            })(
              <Input
                placeholder={formatMessage({ id: 'app.dm.product.service.info.name.place' })}
              />,
            )}
          </FormItem>

          <FormItem
            label={formatMessage({ id: 'app.dm.product.service.info.label' })}
            colon={false}
          >
            {form.getFieldDecorator('label', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'app.dm.product.service.info.label.place' }),
                },
              ],
            })(
              <Input
                placeholder={formatMessage({ id: 'app.dm.product.service.info.label.place' })}
              />,
            )}
          </FormItem>

          <FormItem
            label={formatMessage({ id: 'app.dm.product.service.info.params' })}
            colon={false}
          >
            <List
              size="small"
              bordered
              dataSource={paramList}
              renderItem={(item, index) => (
                <List.Item
                  actions={[
                    <a key="list-loadmore-edit" onClick={() => this.editParam(item, index)}>
                      <FormattedMessage id="app.dm.product.service.param.edit" />
                    </a>,
                    <a key="list-loadmore-more" onClick={() => this.handleRemoveItem(index)}>
                      <FormattedMessage id="app.dm.product.service.param.del" />
                    </a>,
                  ]}
                >
                  <Typography.Text mark>
                    <FormattedMessage id="app.dm.product.service.param.label" />
                  </Typography.Text>{' '}
                  {item.label}
                </List.Item>
              )}
            />
            <a onClick={() => this.handleAddParamVisible(true)}>
              +<FormattedMessage id="app.dm.product.service.param.add" />
            </a>
          </FormItem>

          <FormItem label={formatMessage({ id: 'app.dm.product.service.info.desc' })} colon={false}>
            {form.getFieldDecorator('desc', {
              rules: [],
            })(<TextArea rows={4} />)}
          </FormItem>
        </div>
        <AddParamForm {...addParamProps} modalVisible={addParamModalVisible} />
        <EditParamForm {...editParamProps} modalVisible={editParamModalVisible} />
      </Modal>
    );
  }
}
export default AddProductServiceForm;
